<template>
  <div class="wrapper">
<!--    <el-button type="primary" @click="routetest">sdsdsds</el-button>-->

    <div :style="{
      width: '400px',
      height: '80px',
      lineHeight: '80px',
      background: `url(${sinologo}) no-repeat left`,

      margin: '150px  auto 50px auto',
      paddingLeft: '40px',
      textAlign: 'center',
      fontSize: '24px',
      color: 'lightcyan',
      border: '0px solid #42b983'}"><b>文卫通用远程控制平台</b>
    </div>
    <div
        style="margin: 50px auto; background-color: #fff; width: 400px; height: 370px; padding: 20px; border-radius: 5px">
<!--      <div style="margin: 20px; text-align: center; font-size: 24px; border: 0px solid #42b983"><b>登 录</b></div>-->
      <el-form :model="user" :rules="rules" ref="ruleForm">
        <el-form-item label="账号" prop="username">
          <el-input size="big" style="margin: 10px 0; " prefix-icon="el-icon-user" v-model="user.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="el-icon-lock" show-password size="big" style="margin: 10px 0; "
                    v-model="user.password"/>
        </el-form-item>
        <el-form-item>
          <el-button size="big" type="primary" style="margin: 10px 0; width: 100%" @click="login">登录</el-button>
<!--          <el-button size="big" type="info" style="margin: 10px 0; width: 100%">注册</el-button>-->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import service from '@/utils/request.js'
import {resetRoutes, resetRouter} from "@/router";
import {setToken} from "@/utils/auth";

export default {

  data() {
    return {
      sinologo: require('@/assets/sinologo.png'),

      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
        ]
      },
      pathNew1: '',
    }
  },
  methods: {
    routetest(){
      console.log("routetest")
      resetRouter()
      console.log("routetest over")

    },
    menuGroupCheck(){//检查并修正菜单分组，如果菜单组的路径不在用户菜单权限中存在，则修改菜单组路径
      let userStr = sessionStorage.getItem('user')
      let user = JSON.parse(userStr)
      for(let i=0;i<user.menuTreeGroupList.length;i++){
        if(!this.findPath(user.menuTreeGroupList[i].routepath, user.menuTreeGroupList[i].menuTreeList)){
          let pathNew = ''
          pathNew =  this.newPath(user.menuTreeGroupList[i].menuTreeList)
          user.menuTreeGroupList[i].routepath = pathNew
          sessionStorage.setItem('user', JSON.stringify(user))
        }
      }
    },
    newPath(  menuTreeList){
      //找到最小的序号，用最小的序号的菜单作为菜单组的路径
      let xh = null
      for(let i=0; i<menuTreeList.length; i++){
        if(xh == null) {
          xh = menuTreeList[i].xh
        }else{
          if(menuTreeList[i].xh < xh){
            xh = menuTreeList[i].xh
          }
        }
      }
      for(let i=0; i<menuTreeList.length; i++){
        if(menuTreeList[i].xh == xh) {
          if (menuTreeList[i].children != null && menuTreeList[i].children.length > 0) {
              let pathNew = menuTreeList[i].path + '/' + this.newPath(menuTreeList[i].children)
              return pathNew
          } else {
              return menuTreeList[i].path
          }
        }
      }
    },

    //寻找菜单组的路径是否在用户的菜单权限中存在
    findPath(routepath, menuTreeList){
      let routepathArr = []
      let routepathNext = ''
      if(routepath.indexOf('/') != -1){ //-1表示未找到
        routepathArr = routepath.split('/')
      }else{
        routepathArr.push(routepath)
      }
      if(routepathArr[0] == '')
        routepathArr.shift()
      let routepathTmp = routepathArr[0]
      if(routepath.startsWith('/')){
        routepathNext = routepath.substring( routepath.indexOf('/', 1))
      }else {
        routepathNext = routepath.substring(routepath.indexOf('/'))
      }
      for(let i=0; i < menuTreeList.length; i++){
        let routepathTmp2 = menuTreeList[i].path
        if(routepathTmp2.startsWith('/'))
          routepathTmp2 = routepathTmp2.substring(1)
        if(routepathTmp2 == routepathTmp){
          if(routepathArr.length>1 && routepathArr[1] != null && routepathArr[1] != '' ){//有下一级，继续递归
            return this.findPath(routepathNext, menuTreeList[i].children)
          }else {//无下一级，结束递归
            return true
          }
        }
      }
      return false
    },
    login() {
      //注意，这里测试直接放行
      // this.$message.success("登录成功")
      // this.$router.push('/')
      // return;
      this.$refs['ruleForm'].validate(valid => {
            if (valid) {
              service.post('/user/login', this.user).then(res => {
                    if (res.data.code == 20000) {
                      this.$message.success("登录成功")
                      sessionStorage.setItem('user', JSON.stringify(res.data.data))
                      // sessionStorage.setItem('menurights', JSON.stringify(res.data.data.menuList))
                      this.menuGroupCheck()
                      resetRoutes()
                      // let str = JSON.stringify({"affix":true})
                      // console.log(str)
                      this.$store.dispatch('tagsView/delAllViews')
                      let userStr = sessionStorage.getItem('user')
                      let user = JSON.parse(userStr)
                      // console.log(user.menuList)
                      // for(let i=)
                      this.$router.push(user.menuTreeGroupList[0].routepath)
                      setToken(res.data.data.token)
                      this.$store.dispatch('startWebSocket')
                    } else {
                      this.$message.error(res.data.message)
                    }
                  }
              )
            } else {//校验不合理
              return false
            }
          }
      )
    }
  }
}
</script>


<style scoped>
.wrapper {
  height: 100vh;
  background-image: linear-gradient(to bottom right, darkslateblue, lightgrey);
  overflow: hidden;
}
</style>
